package com.ratingbay.console.social;

import java.sql.Timestamp;
import java.util.Calendar;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ratingbay.console.model.User;
import com.ratingbay.console.service.IUserService;

public class SigninHelper{

    private final IUserService userService;
    public SigninHelper(IUserService userService) {
        this.userService = userService;
        this.selfInstance = this;
    }

    public IUserService getUserService(){
        return this.userService;
    }

    public static SigninHelper selfInstance = null;
    public static SigninHelper getInstance(){
        if(null == selfInstance){
            return null;
        }
        return selfInstance;
    }

    public boolean signin(String userName, String email){
        ServletRequestAttributes attrs = 
            (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attrs.getRequest() ;
        HttpSession session = request.getSession();
        if(null != session.getAttribute("userId")){
            return true;
        }

        //use social provider's username login
        User user = this.userService.findByUsername(userName);
        if (user != null) {
            user.setLastLoginTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
            this.userService.save(user);
            session.setAttribute("userId", user.getId());
            return true;
        } else {
            return false;
        }
    }
}
